package com.example.gymlearning.controller;

import com.example.gymlearning.dto.request.LoginRequest;
import com.example.gymlearning.dto.request.RegisterRequest;
import com.example.gymlearning.dto.response.UserResponse;
import com.example.gymlearning.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @GetMapping("/register")
    public String showRegisterPage(Model model) {
        model.addAttribute("registerRequest", new RegisterRequest());
        return "register";
    }

    @GetMapping("/login")
    public String showLoginPage(Model model) {
        model.addAttribute("loginRequest", new LoginRequest());
        return "login";
    }

    @GetMapping("/index")
    public String showIndexPage(HttpSession httpSession, Model model) {
        System.out.println("=== 访问首页 ===");

        // 检查Session中的用户
        UserResponse user = (UserResponse) httpSession.getAttribute("user");
        System.out.println("Session ID: " + httpSession.getId());
        System.out.println("Session中的用户: " + user);

        if(user != null){
            //session有效直接显示首页
            model.addAttribute("user", user);
            System.out.println("用户存在，显示已登录状态的首页");
            return "indexPage";
        } else {
            //session失效，但不是跳转到登录页，而是显示未登录状态的首页
            System.out.println("显示未登录的首页");
            return "indexPage";
        }
    }

    @PostMapping("/register")
    public String register(@ModelAttribute RegisterRequest request,
                           HttpSession session,
                           Model model,
                           RedirectAttributes redirectAttributes) {

        System.out.println("=== 注册请求开始 ===");
        System.out.println("接收到用户名: " + request.getUsername());

        try {
            UserResponse user = userService.register(request);
            System.out.println("注册成功，用户ID: " + user.getId());

            // 设置用户到Session
            session.setAttribute("user", user);
            System.out.println("用户已设置到Session: " + user.getUsername());

            // 确保Session立即生效
            session.setMaxInactiveInterval(30 * 60); // 30分钟

            System.out.println("准备重定向到首页");

            // 标记来源为注册成功
            redirectAttributes.addFlashAttribute("entrySource", "register");

            // 使用redirect保持Session
            return "redirect:/auth/index";

        } catch (RuntimeException e) {
            System.out.println("注册异常: " + e.getMessage());
            model.addAttribute("error", e.getMessage());
            model.addAttribute("registerRequest", request);
            return "register";
        }
    }

    @PostMapping("/login")
    public String login(@Valid @ModelAttribute LoginRequest request,
                       BindingResult bindingResult,
                       HttpSession session,
                       Model model,
                       RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            return "login";
        }
        
        try {
            UserResponse user = userService.login(request);
            session.setAttribute("user", user);
            // 标记来源为直接登录
            redirectAttributes.addFlashAttribute("entrySource", "login");
            return "redirect:/auth/index";
        } catch (RuntimeException e) {
            model.addAttribute("error", e.getMessage());
            model.addAttribute("username", request.getUsername());
            return "login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        session.invalidate();
        return "redirect:/auth/login";
    }

    @GetMapping("/check-username")
    @ResponseBody
    public Map<String, Object> checkUsername(@RequestParam String username) {
        Map<String, Object> result = new HashMap<>();
        boolean exists = userService.isUserNameExist(username);
        result.put("available", !exists);
        result.put("message", exists ? "用户名已存在" : "用户名可用");
        return result;
    }
}